package com.zoroki.hmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zoroki.hmusic.constant.MessageConstant;
import com.zoroki.hmusic.entity.PlaylistSong;
import com.zoroki.hmusic.entity.Song;
import com.zoroki.hmusic.entity.User;
import com.zoroki.hmusic.es.EsSongRepository;
import com.zoroki.hmusic.mapper.SongMapper;
import com.zoroki.hmusic.service.IFavoriteSongService;
import com.zoroki.hmusic.service.ILyricsService;
import com.zoroki.hmusic.service.IPlaylistSongService;
import com.zoroki.hmusic.service.ISongService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zoroki.hmusic.util.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zoroki
 * @since 2023-05-10
 */
@Service
@Slf4j
public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements ISongService {

    @Autowired
    private SongMapper songMapper;
    @Autowired
    private ILyricsService lyricsService;

    @Autowired
    private IPlaylistSongService playlistSongService;

    @Autowired
    private IFavoriteSongService favoriteSongService;

    @Autowired
    private EsSongRepository esSongRepository;


    @Override
    public int addSong(Song song) {
        int insert = songMapper.insert(song);
        if (insert > 0) {
            Song newSong = songMapper.selectById(song.getId());
            try{
                esSongRepository.save(newSong);
            }catch (Exception e){
                log.error("esSong添加失败:{}",e.getMessage());
                return -1;
            }
            return 1;
        }
        return -1;
    }

    @Override
    public int deleteSong(int id) {
        //删除playlist关联
        playlistSongService.deletePlaylistSongBySongId(id);
        //删除收藏关联
        favoriteSongService.deleteFavoriteSongBySongId(id);
        Song song = songMapper.selectById(id);
        if (song.getUrl() != null) {
            //删除音乐
            String avatar = song.getUrl();
            String fileName = avatar.substring(avatar.lastIndexOf("/") + 1);
            QiniuUtil.deleteFile(MessageConstant.FOLDER_MUSIC + fileName);
        }
        int delete = songMapper.deleteById(id);

        //删除歌词
        if (song.getLyricsId() != null) {
            lyricsService.deleteLyricsById(song.getLyricsId());
        }

        if (delete > 0) {
            esSongRepository.deleteById(String.valueOf(id));
            return 1;
        }
        return -1;
    }

    @Override
    public List<Song> getSongList(int userId) {
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return songMapper.selectList(wrapper);
    }

    @Override
    public Page<Song> getSongPage(int userId, int currentPage, int pageSize) {
        QueryWrapper<Song> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return songMapper.selectPage(new Page<>(currentPage, pageSize), wrapper);
    }

    @Override
    public Song findSongById(int id) {
        return songMapper.selectById(id);
    }

    @Override
    public List<Song> findSongByPlaylistId(int playlistId) {
        List<PlaylistSong> playlistSongs = playlistSongService.findPlaylistSongByPlaylistId(playlistId);

        List<Song> songs = new ArrayList<>();
        playlistSongs.forEach(playlistSong -> {
            QueryWrapper<Song> songQueryWrapper = new QueryWrapper<>();
            songQueryWrapper.eq("id", playlistSong.getSongId());

            Song song = songMapper.selectOne(songQueryWrapper);
            songs.add(song);
        });

        return songs;
    }

    @Override
    public Song updateSong(Song song) {
        int update = songMapper.updateById(song);
        if (update > 0) {
            try{
                esSongRepository.save(song);
            }catch (Exception e){
                log.error("esSong更新失败:{}",e.getMessage());
                return null;
            }
            return song;
        }
        return null;
    }

    @Override
    public SearchHits<Song> findSongByKeyword(String keyword) {
        return esSongRepository.findSongByNameOrSingerOrLyricistOrComposerOrRemark(keyword, keyword, keyword, keyword, keyword);
    }

    @Override
    public org.springframework.data.domain.Page<Song> getSongPageByKeyword(String keyword, int pages) {
        Sort sort = Sort.by(Sort.Order.asc("createdAt"));
        return esSongRepository.findSongsByNameOrSingerOrLyricistOrComposerOrRemark(keyword, keyword, keyword, keyword, keyword, PageRequest.of(pages, 6, sort));
    }

    @Override
    public org.springframework.data.domain.Page<Song> getNewSongFromEs(int number) {
        Sort sort = Sort.by(Sort.Order.desc("createdAt"));
        return  esSongRepository.findAll(PageRequest.of(0, number, sort));
    }
}
